package com.estar.integaration.Util;

import com.alibaba.fastjson.JSONObject;
import com.estar.integaration.Service.IChildAcodeService;
import com.estar.integaration.Service.IProductionScheduleService;
import com.estar.integaration.entity.*;
import com.google.gson.JsonObject;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Author: YJL
 * Date: 2021/11/22 16:39
 **/
@Component
@NoArgsConstructor
public class MaterialUtil {

  @Autowired
  IChildAcodeService bridgeChildAcodeService;
  private static IChildAcodeService childAcodeService;

  /**
   * 同张表存在相同物料合并
   * @param materialVOList
   * @return
   */
  public static List<MaterialVo> mergeOneExecelSameMaterial(List<MaterialVo> materialVOList){
    //根据物料号存
    HashMap<String,MaterialVo> materialVOHashMap = new HashMap<>();
    //去重后List
    List<MaterialVo> noSameMaterialList = new ArrayList<>();

    for(MaterialVo mVO : materialVOList){
      //materialvoid
      mVO.setId(Util.getUUID());

      if(!materialVOHashMap.containsKey(mVO.getMaterialNo())){

        materialVOHashMap.put(mVO.getMaterialNo(),mVO);

      }else {
        //存在相同，取出Hash中的,与List中的指向同一个
        MaterialVo hashmVO = materialVOHashMap.get(mVO.getMaterialNo());
        //改变List中的
        hashmVO.setPlanQuantity(hashmVO.getPlanQuantity() + mVO.getPlanQuantity());

      }

    }

    //导出Hash
    noSameMaterialList.addAll(materialVOHashMap.values());

    return noSameMaterialList;

  }

  /**
   * 设置紧急
   * @param materialVOList
   * @return
   */
  public static List<MaterialVo> setIsUrgentandProductId(List<MaterialVo> materialVOList,Boolean isUrgent,ProductDb productDb){

    for(MaterialVo mVO : materialVOList){

      mVO.setIsUrgent(isUrgent);

      mVO.setProductId(productDb.getId());

      mVO.setACode(productDb.getACode());

    }

    return materialVOList;

  }

  /**
   * 解析多A码
   * @param productMachineInfo
   * @param
   */
  public static List<ChildAcode> parseSomeAcode_WriteinSQL(ProductMachineInfo productMachineInfo, IChildAcodeService childAcodeServic, String aPId){

    String ACode = productMachineInfo.getProductDb().getACode();

    List<String> codeList = getAllAcode(ACode);
    //用于插入Batch
    List<ChildAcode> childAcodeList = new ArrayList<>();

    for(String s : codeList ){

      ChildAcode childAcode = new ChildAcode();

      childAcode.setFullACodeId(aPId);

      childAcode.setProductId(productMachineInfo.getProductDb().getId());

      childAcode.setId(Util.getUUID());

      String[] haveStickStr = null;

      if(s.contains("-")){

        haveStickStr = s.split("-");

        childAcode.setACode(haveStickStr[0]);

        childAcode.setChildContent(haveStickStr[1]);


      }else {

        childAcode.setACode(s);

        childAcode.setChildContent(null);

      }

      childAcodeList.add(childAcode);

    }
    //加入数据库
    childAcodeService.saveBatch(childAcodeList);

    return childAcodeList;

  }

  /**
   * 拆分Acode
   * @param ACode
   * @return
   */
  public static List<String> getAllAcode(String ACode){

    String[] tmpArray = null;

    if(ACode.contains(",")){

      tmpArray = StringUtil.splitStrByChar(ACode,",");

    }else if(ACode.contains("，")){

      tmpArray = StringUtil.splitStrByChar(ACode,"，");

    }else if(ACode.contains("，")){

      tmpArray = StringUtil.splitStrByChar(ACode,"，");

    }else if(ACode.contains("，")){

      tmpArray = StringUtil.splitStrByChar(ACode,"，");

    }else {

      tmpArray = new String[]{ACode};

    }

    return new ArrayList<String>(Arrays.asList(tmpArray));

  }


  /**
   * 排期取出形成Hash
   * @return
   */
  public static HashMap<String, Date> getScheduleHashMap(IProductionScheduleService productionScheduleService){
    //查询出全部交期
    List<ProductionSchedule> productionScheduleList = productionScheduleService.selectAllPs();
    //转换成Hash
    HashMap<String,Date> scheduleHash = new HashMap<>();

    productionScheduleList.forEach( p -> scheduleHash.put(p.getACode(),p.getStandardComeTime()));

    return scheduleHash;

  }

  public static List<Material> parseMaterialVOList2Material(List<MaterialVo> materialVoList, Date delivery, AcodeProductVo fullCode){

    List<Material> materials = new ArrayList<>();

    for(MaterialVo materialVo : materialVoList){

      Material material = Material.cloneMVO2M(materialVo);

      material.setId(Util.getUUID());

      material.setDelivery(delivery);
      //绑定完整A码VOId
      material.setACodeProductVo(fullCode.getId());

      material.setPlanQuantity(materialVo.getPlanQuantity());

      material.setUnpurchased(materialVo.getPlanQuantity());

      material.setPurchased(0d);

      material.setACode(fullCode.getFullACode());

      materials.add(material);

    }

    return materials;

  }

  /**
   * 通过MaterialList形成HashMap
   * @param materialList
   * @return
   */
  public static HashMap<String,Material> getMaterialNoMaterialHashByList(List<Material> materialList){
    HashMap<String,Material> materialHashMap = new HashMap<>();
    materialList.forEach(m -> materialHashMap.put(m.getMaterialNo(),m));
    return materialHashMap;
  }


  /**
   * 所有materialVo转成material
   *
   * @param productId
   * @param delivery
   * @return
   */
  public static List<Material> changeAllMaterialVo2Material(List<MaterialVo> materialVoList,String productId,Date delivery,String aCodeProductVoId){

//    List<MaterialVo> materialVoList = materialVoService.getMaterialByProductId(productId);

    List<Material> materialList = new ArrayList<>();

    materialVoList.forEach(m -> {
      Material material = Material.cloneMVO2M(m);
      material.setDelivery(delivery);
      material.setProductId(productId);
      materialList.add(material);
    });

    return materialList;

  }

  /**
   * 未购扣掉
   * @param material
   * @param num
   * @return
   */
  public static Double minusUnPurchaseDepartwithNum(Material material,Double num){
    Double oldValue = material.getUnpurchased() ;//已购
    Double newValue = oldValue-num;
    return newValue;
  }

  @PostConstruct
  public void init(){
    //注入对象
    childAcodeService = bridgeChildAcodeService;
  }

  public static Material parseMaterialFromJson(JSONObject materialJsonObject){
    Date date = new Date(materialJsonObject.getString("delivery"));
    Material material = new Material(
        materialJsonObject.getString("id"),
        materialJsonObject.getString("materialNo"),
        materialJsonObject.getString("materialName"),
        materialJsonObject.getString("figureNo"),
        materialJsonObject.getString("specs"),
        materialJsonObject.getString("brand"),
        materialJsonObject.getDouble("quantity"),
        materialJsonObject.getDouble("planQuantity"),
        materialJsonObject.getString("price"),
        materialJsonObject.getDouble("totalPrice"),
        materialJsonObject.getString("bomRemark"),
        date,
        materialJsonObject.getDouble("purchased"),
        materialJsonObject.getDouble("unpurchased"),
        materialJsonObject.getDouble("thisPurchase"),
        materialJsonObject.getDouble("backGoods"),
        materialJsonObject.getDouble("inventory"),
        "",
        materialJsonObject.getString("approvalCode"),
        materialJsonObject.getBoolean("isUrgent"),
        materialJsonObject.getString("inventoryRemark"),
        materialJsonObject.getString("aCodeProductVo"),
        materialJsonObject.getString("productId"),
        materialJsonObject.getString("ACode"),
            ""
        );

    return material;
  }



  public static List<Material> filterListUnpurchasedBiggerThanZero(List<Material> materialList){
    List<Material> sortedPurL = materialList.stream()
            .filter(x -> x.getUnpurchased() > 0 )
            .sorted(Comparator.comparing(Material::getMaterialNo))
            .collect(Collectors.toList());
    return sortedPurL;
  }
}
